package com.hzw.code.fast.sys.controller;

import com.hzw.code.fast.sys.dto.SysUserDto;
import com.hzw.code.redis.dao.RedisDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;


/**
 * 测试控制器
 */
@RestController
@RequestMapping("test")
@Slf4j
@RequiredArgsConstructor
public class TestController {

    private final RedisDao<String, SysUserDto> redisDao;

    /**
     * 全部拒绝
     * @return
     */
    @DenyAll()
    @GetMapping("/denyAll")
    public Object denyAll(){
        return "全部拒绝";
    }

    /**
     * 全部通过
     * @return
     */
    @PermitAll()
    @GetMapping("/permitAll")
    public Object permitAll(){
        return "全部通过";
    }

    /**
     * 代表标注的方法只要具有TEST, ADMIN任意一种权限就可以访问。这里可以省略前缀ROLE_，实际的权限可能是ROLE_TEST
     * @return
     */
    @RolesAllowed({"TEST","ADMIN"})
    @GetMapping("/double/auth")
    public Object doubleAuth(){
        return "两个只需满足其中一个的权限！";
    }

    /**
     * 需要TEST权限
     * @return
     */
    @Secured("ROLE_TEST")
    @GetMapping("/secured")
    public Object secured(){
        return "secured 权限";
    }

    /**
     *
     * @return
     */
    @Secured({"ROLE_TEST","ROLE_ADMIN"})
    @GetMapping("/securedMany")
    public Object securedMany(){
        return "securedMany 权限";
    }

    /**
     * 两个只需满足其中一个的权限
     * @return
     */
    @PreAuthorize("hasAnyRole('ROLE_TEST','ROLE_ADMIN')")
    @GetMapping("/test/auth")
    public Object testAuth(){
        return "两个只需满足其中一个的权限！";
    }

    /**
     * ROLE_ADMIN 权限
     * @return
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/admin/auth")
    public Object adminAuth(){
        SysUserDto userDto = new SysUserDto();
        userDto.setUserName("大大咧咧");
        userDto.setUserEmail("hzw2312@sina.com");
        userDto.setUserPhone("13985046628");
        redisDao.setKey("fast_user_dao",userDto);
        return "ROLE_ADMIN 权限！";
    }

    /**
     * 两个只需满足其中一个的权限
     * @param test
     * @return
     */
    @PreAuthorize("hasAnyAuthority('TEST','TEST_USER_GET')")
    @GetMapping("/{test}")
    public Object test(@PathVariable String test){
        return test + " 你好！";
    }

    /**ss
     * 获得当前用户信息
     * @return
     */
    @PreAuthorize("hasAuthority('TEST_USER_GET')")
    @GetMapping("/user")
    public Object getUser(){
        return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
